package org.liangsy.rest.user.test;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import java.util.Collections;
import java.util.Scanner;

public class MybatisGenerator {

    // 配置常量
    private static final String OUTPUT_DIR = "/rest-service/src/main/java";
    private static final String XML_DIR = "/rest-service/src/main/resources/mapper";
    private static final String AUTHOR = "liangsy";
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/templet_test_v1?useSSL=false&characterEncoding=utf8";
    private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final String PARENT_PACKAGE = "org.liangsy.rest";
    private static final String SUPER_CONTROLLER = "org.liangsy.rest.common.BaseController"; // 自定义控制器基类（可选）

    public static void main(String[] args) {
        AutoGenerator generator = new AutoGenerator(createDataSourceConfig());
        generator.global(createGlobalConfig())
                .packageInfo(createPackageConfig())
                .strategy(createStrategyConfig())
                .template(createTemplateConfig())
                .execute(new FreemarkerTemplateEngine());
    }

    private static GlobalConfig createGlobalConfig() {
        String projectPath = System.getProperty("user.dir");
        return new GlobalConfig.Builder()
                .outputDir(projectPath + OUTPUT_DIR)
                .author(AUTHOR)
                .dateType(DateType.ONLY_DATE)
                .disableOpenDir() // 禁止打开输出目录
                .build();
    }

    private static DataSourceConfig createDataSourceConfig() {
        return new DataSourceConfig.Builder(DATABASE_URL, USERNAME, PASSWORD)
                .typeConvert(new MySqlTypeConvert())
                .build();
    }

    private static PackageConfig createPackageConfig() {
        String projectPath = System.getProperty("user.dir");
        return new PackageConfig.Builder()
                .parent(PARENT_PACKAGE)
                .entity("entity")
                .mapper("mapper")
                .service("service")
                .serviceImpl("service.impl")
                .controller("controller")
                .pathInfo(Collections.singletonMap(
                        OutputFile.xml,
                        projectPath + XML_DIR
                ))
                .build();
    }

    private static StrategyConfig createStrategyConfig() {
        return new StrategyConfig.Builder()
                .addInclude(getTableNames())
                .addTablePrefix("t_")
                .entityBuilder()
                .naming(NamingStrategy.underline_to_camel)
                .columnNaming(NamingStrategy.underline_to_camel)
                .enableLombok()
                .addTableFills(new Column("create_time", FieldFill.INSERT))
                .addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE))
                .mapperBuilder()
                .enableBaseResultMap()
                .enableBaseColumnList()
                .serviceBuilder()
                .formatServiceFileName("%sService") // 服务接口命名
                .formatServiceImplFileName("%sServiceImpl") // 服务实现类命名
                .controllerBuilder()
                .enableRestStyle() // 开启REST风格控制器
                .enableHyphenStyle() // URL使用连字符格式
//                .superClass(SUPER_CONTROLLER) // 自定义基类（可选）
                .build();
    }

    private static TemplateConfig createTemplateConfig() {
        return new TemplateConfig.Builder()
                // 使用默认模板生成所有层
                .build();
    }

    private static String[] getTableNames() {
        System.out.println("请输入表名（多个表用逗号分隔）：");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine().trim();
        scanner.close();
        if (!input.isEmpty()) {
            return input.split(",");
        }
        throw new RuntimeException("必须输入至少一个表名！");
    }
}